package net.sppan.blog.controller.admin;

import java.io.UnsupportedEncodingException;

import com.jfinal.aop.Clear;
import com.jfinal.kit.StrKit;

import net.sppan.blog.annotation.RequiresPermissions;
import net.sppan.blog.controller.BaseController;
import net.sppan.blog.model.User;
import net.sppan.blog.utils.WebUtils;

@RequiresPermissions
public class AdminController extends BaseController {
	
	@RequiresPermissions(key="admin:index")
	public void index(){
		render("welcome.html");
	}

	@Clear
	public void login_page(){
		render("login.html");
	}
	
	/**
	 * 执行登录
	 */
	@Clear
	public void login() {
		String username = getPara("username");
		String password = getPara("password");
		String remember = getPara("remember", "0");
		System.out.println(WebUtils.pwdEncode(password));
		User user = User.dao.login(username, WebUtils.pwdEncode(password));
		if(StrKit.notNull(user)) {
			user.update();
			try {
				WebUtils.loginUser(this, user, remember.equals("1"));
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
				renderJson(false, e.getMessage());
				return;
			}
			renderJson(true, "登录成功");
		}else{
			renderJson(false, "登录失败，用户名或者密码错误");
		}
	}
	
	/**
	 * 执行登出
	 * @return void	返回类型
	 * @throws
	 */
	@Clear
	public void logout() {
		WebUtils.logoutUser(this);
		redirect("/admin/index");
	}
}
